# -*- coding: UTF-8 -*-
# 使用穷举法，得到最优结果
from itertools import combinations
import random
import AoI_SP
from seller_SP import SellerAoISP
from buyer_SP import BuyerAoISP
from util import Util


def chooseSeller_OPT(s, bindex, budget, T):
    qseller = len(s)
    w_all = range(qseller)
    bestw = []
    bestAoI = 2**31
    # 选中组合长度不断递增
    for wlen in range(1, qseller+1):
        w_comb = list(combinations(w_all, wlen))
        stop = 1
        # 遍历每种组合
        for sg in w_comb:
            sg = list(sg)
            # 计算预算
            budget_sg = 0
            for si in sg:
                budget_sg += s[si].price[bindex]
            # 如果超预算,继续
            if(budget_sg > budget):
                continue
            # 未超预算
            stop = 0
            aoi = AoI_SP.getAoI(s, sg, T)
            if(aoi < bestAoI):
                bestAoI = aoi
                bestw = sg
        # 若当前长度全部超预算，循环终止
        if stop == 1:
            break
    return bestw, bestAoI


def OPT(T, s, b):
    bw = []  # 各个买家选择结果集合
    baoi = []
    for buyer in b:
        w, aoi = chooseSeller_OPT(s, buyer.id, buyer.budget, T)
        bw.append(w)
        baoi.append(aoi)
    return bw, baoi


if(__name__ == "__main__"):
    # 参数
    qseller = 18  # 卖家数量
    qbuyer = 2  # 买家数量
    budget = 80  # 初始预算
    T = 100  # 时间段数量
    mode = 'w'  # 数据存取模式

    # 初始化
    s = []  # 卖家集合
    b = []  # 买家集合
    util = Util()
    for i in range(qseller):
        seller = SellerAoISP(i, qbuyer, T)
        s.append(seller)
    for i in range(qbuyer):
        buyer = BuyerAoISP(i, T, random.randint(budget-10, budget+10))
        b.append(buyer)
    buyerw, buyeraoi = OPT(T, s, b)
    print(buyerw, buyeraoi)
